import LoadInfo from '@/components/LoadInfo';
import { ParkingOrderStatus, ParkingOrderTableItem, PayStatus } from '@/pages/ParkingOrder/types.d';
import { Auths, Role } from '@/utils/types.d';
import {
  ModalForm,
  ProFormTextArea,
  ProTable,
  ActionType,
  ProColumns,
} from '@ant-design/pro-components';
import { Badge, message, Table } from 'antd';
import { useRef, useState } from 'react';
import { useModel } from 'umi';
import CheckResult from '../components/CheckResult';
import { cancelMerge, checkOrderMerge, confirmMerge, queryMergeOrders } from '../service';
import { CheckMergeResult } from '../types.d';

// const obj: CheckMergeResult = {
//   prevInfo: {
//     prevActual: 1000,
//     prevPayable: 3000,
//   },
//   mergeInfo: {
//     _id: 'xxxx',
//     orderNo: '123456789',
//     newOrderInfo: {
//       inTime: new Date('2021-01-01 12:00:00'),
//       outTime: new Date('2021-01-01 13:00:00'),
//       isCarOut: false,
//       payableAmount: 2000,
//       actualAmount: 1000,
//     },
//     operAccount: 'admin',
//     operName: '管理员',
//     operTime: new Date('2021-01-01 12:00:00'),
//     plateNumber: '浙EMIKO2',
//     ownerId: 'movebroad',
//     remark: '',
//     status: 0,
//     createTime: new Date('2021-01-01 12:00:00'),
//     orderInfos: [],
//   },
// };

const OrderList = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const [visible, setVisible] = useState<boolean>(false);
  // const [mergeRecord, setMergeRecord] = useState<CheckMergeResult | null>(null);
  const [checkResult, setCheckResult] = useState<CheckMergeResult | null>(null);
  const [orderNos, setOrderNos] = useState<string[]>([]);
  const [step, setStep] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const ref = useRef<ActionType>();
  const auths = currUser?.auth ? new Set(currUser.auth.mergeOrder || []) : new Set();
  const ifCreate = auths.has(Auths.CREATE);
  const columns: ProColumns<ParkingOrderTableItem>[] = [
    {
      title: '所属用户',
      align: 'center',
      hideInTable: currUser?.role != Role.ADMIN,
      dataIndex: ['ownerInfo', 'ownerName'],
      hideInSearch: true,
    },
    {
      title: '订单编号',
      dataIndex: 'orderNo',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      renderText: (text, record) => {
        if (record.isImport) return text + '(导)';
        return text;
      },
    },
    {
      title: '路段名称',
      dataIndex: 'parkingLotId',
      hideInForm: true,
      hideInSearch: true,
      align: 'center',
      render: (_, record) => record.parkingLotName,
    },
    {
      title: '泊位编号',
      dataIndex: 'spotId',
      hideInForm: true,
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '车牌号码',
      dataIndex: 'plateNumber',
      align: 'center',
      hideInForm: true,
    },
    {
      title: '车辆类型',
      dataIndex: 'vehicleType',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      width: 100,
      valueEnum: {
        0: { text: '普通小型车' },
        1: { text: '普通大型车' },
        2: { text: '新能源小型车' },
        3: { text: '新能源大型车' },
        4: { text: '警车' },
        5: { text: '武警' },
      },
      renderText: (_, record) => {
        if (!record.plateNumber) return '暂无数据';
        return _;
      },
    },
    {
      title: '订单状态',
      dataIndex: 'status',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      valueEnum: {
        1: { text: '正常', status: 'Success' },
        2: { text: '未开票', status: 'Error' },
        3: { text: '车牌未录入', status: 'Error' },
        4: { text: '欠费', status: 'Error' },
        99: { text: '未知异常', status: 'Error' },
        1001: { text: '已作废', status: 'Error' },
      },
      render: (_, record) => {
        if (record.canceled) return <Badge color="#666" text="已作废" />;
        switch (record.status) {
          case ParkingOrderStatus.NORMAL:
            return <Badge status="success" text="正常" />;
          case ParkingOrderStatus.ARREAR:
            return <Badge status="error" text="欠费" />;
          case ParkingOrderStatus.NOT_ENTRIED:
            return <Badge status="error" text="车牌未录入" />;
          case ParkingOrderStatus.NOT_PRINT:
            return <Badge status="error" text="未开票" />;
          default:
            return <Badge status="error" text="未知异常" />;
        }
      },
    },
    {
      title: '是否结束',
      dataIndex: 'isEnded',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      valueEnum: {
        true: { text: '结束', status: 'Default' },
        false: { text: '进行中', status: 'Processing' },
      },
      render: (_, record) => {
        if (record.canceled) return '-';
        if (record.isEnded) return <Badge status="default" text="结束" />;
        return <Badge status="processing" text="进行中" />;
      },
    },
    {
      title: '应收金额',
      dataIndex: 'payableAmount',
      hideInSearch: true,
      width: 80,
      align: 'center',
      valueType: 'money',
      renderText: (text) => (text / 100).toFixed(2),
    },
    {
      title: '实收金额',
      dataIndex: 'actualAmount',
      hideInSearch: true,
      align: 'center',
      valueType: 'money',
      renderText: (text) => (text / 100).toFixed(2),
    },
    {
      title: '支付状态',
      dataIndex: 'payStatus',
      align: 'center',
      hideInForm: true,
      hideInSearch: true,
      valueEnum: {
        0: { text: '免费', status: 'Success' },
        1: { text: '未付', status: 'Error' },
        2: { text: '未结清', status: 'Processing' },
        3: { text: '已结清', status: 'Success' },
        4: { text: '已退款', status: 'Default' },
        5: { text: '待退款', status: 'Error' },
        99: { text: '未结算', status: 'Default' },
      },
      render: (_, record) => {
        if (record.canceled) return '-';
        switch (record.payStatus) {
          case PayStatus.FREE:
            return <Badge status="success" text="免费" />;
          case PayStatus.WAITING:
            return <Badge status="error" text="未付" />;
          case PayStatus.PARI_PAID:
            if (record.payableAmount == record.actualAmount)
              return <Badge status="processing" text="已支付" />;
            return <Badge status="processing" text="未结清" />;
          case PayStatus.FULL_PAID:
            return <Badge status="success" text="已结清" />;
          case PayStatus.REFUNDED:
            return <Badge status="default" text="已退款" />;
          case PayStatus.WAIT_REFUND:
            return <Badge status="error" text="待退款" />;
          default:
            return <Badge status="default" text="未结算" />;
        }
      },
    },
    {
      title: '开始时间',
      dataIndex: 'startTime',
      hideInForm: true,
      hideInTable: true,
      valueType: 'dateTime',
    },
    {
      title: '结束时间',
      dataIndex: 'endTime',
      hideInForm: true,
      hideInTable: true,
      valueType: 'dateTime',
    },
    {
      title: '驶入时间',
      dataIndex: 'inTime',
      align: 'center',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '驶出时间',
      dataIndex: 'outTime',
      align: 'center',
      valueType: 'dateTime',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '订单来源',
      dataIndex: 'isImport',
      hideInTable: true,
      hideInForm: true,
      hideInSearch: true,
      valueEnum: {
        true: { text: '外部导入' },
        false: { text: '系统生成' },
      },
    },
  ];
  return (
    <>
      <ProTable<ParkingOrderTableItem>
        columns={columns}
        rowKey="orderNo"
        scroll={{ x: true }}
        search={{ labelWidth: 'auto' }}
        style={{ whiteSpace: 'nowrap' }}
        actionRef={ref}
        columnEmptyText="暂无数据"
        pagination={false}
        debounceTime={300}
        request={queryMergeOrders}
        rowSelection={
          ifCreate && {
            selections: [Table.SELECTION_ALL, Table.SELECTION_INVERT],
          }
        }
        tableAlertRender={({ selectedRowKeys, onCleanSelected }) => (
          <span>
            已选 {selectedRowKeys.length} 项
            <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
              取消选择
            </a>
          </span>
        )}
        tableAlertOptionRender={({ selectedRows }) => {
          return (
            ifCreate && (
              <a
                onClick={async () => {
                  if (selectedRows.length < 2) {
                    message.error({ content: '请选择2个及以上的待合并订单', key: 'merge_order' });
                    return false;
                  }
                  const orderNos = selectedRows.map((item) => item.orderNo);
                  setOrderNos(orderNos);
                  setVisible(true);
                  return true;
                }}
              >
                合并订单
              </a>
            )
          );
        }}
      />
      <ModalForm
        title="合并订单操作"
        visible={visible}
        onFinish={async (values) => {
          if (step == 0) {
            setLoading(true);
            const res = await checkOrderMerge(orderNos);
            setLoading(false);
            if (!res.success) {
              message.error({ content: res.message, key: 'merge_order', duration: 5 });
              return false;
            }
            setCheckResult(res.data);
            setStep(1);
            return true;
          }
          if (step == 1) {
            if (!checkResult) {
              message.error({ content: '无法获取核验信息', key: 'merge_order' });
              return false;
            }
            setLoading(true);
            const res = await confirmMerge(checkResult.mergeInfo._id, values.remark);
            setLoading(false);
            if (!res.success) {
              message.error({ content: res.message, key: 'merge_order' });
              return false;
            }
            message.success({ content: '合并成功', key: 'merge_order' });
            setVisible(false);
            setStep(0);
            setCheckResult(null);
            setOrderNos([]);
            if (ref?.current?.clearSelected) ref?.current?.clearSelected();
            ref?.current?.reload();
            return true;
          }

          return false;
        }}
        modalProps={{
          maskClosable: false,
          destroyOnClose: true,
          onCancel: async () => {
            if (step == 1 && checkResult) {
              await cancelMerge(checkResult.mergeInfo._id);
            }
            if (ref?.current?.clearSelected) ref?.current?.clearSelected();
            ref?.current?.reload();
            setStep(0);
            setVisible(false);
            setOrderNos([]);
            return true;
          },
        }}
      >
        {step == 0 &&
          (loading ? (
            <LoadInfo loading loadingText="正在核验，请稍后..." />
          ) : (
            <>
              即将合并订单:{' '}
              {orderNos.map((item) => (
                <div>{item}</div>
              ))}
              请确认是否提交审核
            </>
          ))}
        {step == 1 && loading ? (
          <LoadInfo loading loadingText="正在合并，请稍后..." />
        ) : (
          <>
            {checkResult ? (
              <>
                所选订单可合并，以下为合并信息，请确认是否合并：
                <CheckResult checkResult={checkResult} />
                <ProFormTextArea name="remark" label="备注" />
              </>
            ) : (
              <>无法获取审核结果，请稍后重新尝试</>
            )}
          </>
        )}
      </ModalForm>
    </>
  );
};

export default OrderList;
